package com.aijle.videopaper.util;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.aijle.videopaper.widget.IjkVideoViewN;

import org.dync.ijkplayerlib.widget.media.IRenderView;

import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;

public class OverlayHelper {
    private static final String TAG = "OverlayHelper";
    Preferences mPreferences;
    WindowManager mWindowManager;
    IjkVideoViewN videoView = null;
    List<String> videoList;
    int curVideo = 0;
    Context mContext;
    IWidgetManager mWidgetManager;

    public OverlayHelper(Context context, IWidgetManager widgetManager) {
        mContext = context;
        mPreferences = new Preferences(context);
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mWidgetManager = widgetManager;
    }

    public IjkVideoViewN startVideo(String file) {
        closeVideo(false);

        if (videoView == null) {
            // 添加TextView
            videoView = new IjkVideoViewN(mContext);
            mWidgetManager.addView(videoView);
            videoView.setRender(IjkVideoViewN.RENDER_SURFACE_VIEW);
            videoView.setAspectRatio(IRenderView.AR_ASPECT_FILL_PARENT);

            IMediaPlayer.OnPreparedListener preparedListener = new IMediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(IMediaPlayer iMediaPlayer) {
                    int position = mPreferences.getVideoProgress();
                    if (position > 0) {
                        videoView.seekTo(position);
                        mPreferences.setVideoProgress(-1);
                    }
                    updateVolume();
                }
            };
            videoView.setOnPreparedListener(preparedListener);

            IMediaPlayer.OnCompletionListener completionListener = new IMediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(IMediaPlayer iMediaPlayer) {
                    playNext();
                }
            };
            videoView.setOnCompletionListener(completionListener);

            videoView.setmSensor(new IjkVideoViewN.ISensor() {
                @Override
                public void posChanged(int xDistance) {
                    int xOldpos = mPreferences.getVideoXPos();
                    int newXpos = xOldpos - xDistance;
                    if (newXpos >= 0 && newXpos <= 100) {
                        mPreferences.setVideoXPos(newXpos);
                        updateXPos();
                    }
                }
            });
        }

        renderWidth = 0;
        videoView.setVideoPath(file);
        videoView.start();
        View.OnLayoutChangeListener layoutChangeListener = new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
                    int width = view.getWidth();
                    if (width != renderWidth) {
                        renderWidth = width;
                        updateXPos();
                        updateSensor(false);
                    }
                }
            };

        videoView.getmRenderView().getView().addOnLayoutChangeListener(layoutChangeListener);
        updateLayout();
        return videoView;
    }

    int renderWidth = 0;
    boolean isOpen = false;
    boolean canShow = true;

    public IjkVideoViewN playNext() {
        curVideo ++;
        if (curVideo >= videoList.size()) {
            curVideo = 0;
        }
        if (mPreferences.getRandom()) {
            curVideo = (int)Math.floor(Math.random()*videoList.size());
        }
        mPreferences.setVideoIndex(curVideo);
        mPreferences.setVideoProgress(0);
        return startVideo(videoList.get(curVideo));
    }

    public IjkVideoViewN reload() {
        videoList = mPreferences.getVideoList();
        if (videoList.size() > 0 && mPreferences.getAutoOpen()) {
            isOpen = true;
            if (curVideo != mPreferences.getVideoIndex()) {
                mPreferences.setVideoProgress(0);
            }
            curVideo = mPreferences.getVideoIndex();
            if (curVideo >= videoList.size()) {
                curVideo = 0;
                mPreferences.setVideoIndex(0);
                mPreferences.setVideoProgress(0);
            }
            return startVideo(videoList.get(curVideo));
        } else {
            isOpen = false;
            closeVideo(true);
            return null;
        }
    }

    public void toggle() {
        if (canShow) {
            if (isOpen) {
                isOpen = false;
                closeVideo(true);
            } else {
                reload();
            }
        }
    }

    public void open() {
        if (!isOpen) {
            this.toggle();
        }
    }

    public void close() {
        if (isOpen) {
            this.toggle();
        }
    }

    public boolean isShowDesktop() {
        return mPreferences.getShowDesktop();
    }

    public void setCanShow(boolean canShow) {
        if (this.canShow == canShow)
            return;
        this.canShow = canShow;
        if (canShow) {
            if (isOpen) {
                float alpha = mPreferences.getOpacity() / 100.0f;
                mWidgetManager.updateLayout(videoView, alpha);
                resume();
            }
        } else {
            if (isOpen) {
                mWidgetManager.updateLayout(videoView, 0f);
                pause();
            }
        }
    }

    public void updateLayout() {
        if (videoView != null) {
            float alpha = mPreferences.getOpacity() / 100.0f;
            mWidgetManager.updateLayout(videoView, alpha);
        }
    }

    public void switchSound() {
        if (videoView != null) {
            mPreferences.setMute(!mPreferences.getMute());
            updateVolume();
        }
    }

    public void updateVolume() {
        if (videoView != null && videoView.getMediaPlayer() != null) {
            float volume = mPreferences.getVolume() / 100.0f;
            if (mPreferences.getMute()) {
                volume = 0.0f;
            }
            videoView.getMediaPlayer().setVolume(volume, volume);
        }
    }

    public void updateXPos() {
        if (videoView != null && renderWidth > 0) {
            Point point = new Point();
            mWindowManager.getDefaultDisplay().getRealSize(point);
            int totalXWidth = renderWidth - point.x;
            if (totalXWidth > 0) {
                int xpos = mPreferences.getVideoXPos();
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)videoView.getmRenderView().getView().getLayoutParams();
                lp.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
                lp.leftMargin = (int)(- totalXWidth * xpos / 100.0f);
                videoView.getmRenderView().getView().setLayoutParams(lp);
            }
        }
    }

    public void updateSensor(boolean stop) {
        updateSensor(stop, true);
    }

    public void updateSensor(boolean stop, boolean resetx) {
        Log.d(TAG, String.format("updateSensor %b %b", stop, resetx));
        if (mPreferences.getSensor() && !stop) {
            if (videoView != null) {
                videoView.updateSensor(true);
            }
        } else {
            if (videoView != null) {
                videoView.updateSensor(false);
//                if (resetx) {
//                    mPreferences.setVideoXPos(50);
//                    updateXPos();
//                }
            }
        }
    }

    public void pause() {
        if (videoView != null) {
            videoView.pause();
            updateSensor(true, false);
        }
    }

    public void resume() {
        if (videoView != null) {
            videoView.start();
            updateSensor(false);
        }
    }

    public void closeVideo(boolean release) {
        if (videoView != null) {
            videoView.updateSensor(false);

            if (release) {
                mPreferences.setVideoProgress(videoView.getCurrentPosition());
            }
            videoView.stopPlayback();
            videoView.stopBackgroundPlay();
            videoView.stopVideoInfo();
            videoView.release(true);

            if (release) {
                mWidgetManager.removeView(videoView);
                videoView = null;
            }
        }
    }
}
